package com.lancoo.znbkxx.teacher.aibkTestCoach.paperToEvaluation.aibkEvalutionZHT

import android.animation.ObjectAnimator
import android.content.Context
import android.os.Handler
import android.text.Html
import android.util.Log
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.ValueCallback
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkDialog.ShowDialogTools
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.LancooMethod.addClickScale
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseFragment
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseFragmentPagerAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.PaperEvaluationInfor
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToEvaluation.PaperEvaluationInforIndexHelp
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToEvaluation.PaperEvaluationInforIndexHelp.getChildListBean
import com.lancoo.znbkxx.teacher.utils.WebStyleUtils
import com.lancoo.znbkxx.teacher.utils.WebStyleUtils.returnImageUrlsFromHtml
import com.lancoo.znbkxx.teacher.widget.KWebView
import kotlinx.android.synthetic.main.aibk_include_article_view.view.*
import kotlinx.android.synthetic.main.aibk_include_child_answer_title_infor.view.*
import kotlinx.android.synthetic.main.aibk_include_parent_audioplayer_a.view.*
import kotlinx.android.synthetic.main.aibk_include_ques_answer_view.view.*
import kotlinx.android.synthetic.main.aibk_include_ques_assessment.view.*
import kotlinx.android.synthetic.main.aibk_include_ques_web_ask_view.view.*
import kotlinx.android.synthetic.main.aibk_include_question_information_view.view.*
import kotlinx.android.synthetic.main.aibk_fragment_model_splitlayout.view.*
import kotlinx.android.synthetic.main.aibk_include_layout_evaluation_button_view.view.*
import java.util.*

class EvaluationFragmentZht(
        val activity: AppCompatActivity,
        val paperEvaluationInfor: PaperEvaluationInfor,
        val index_A: Int,
        val index_B: Int
) : KBaseFragment(), View.OnClickListener {

    private var rootView: View? = null
    private var isAddView = false
    private var childVpPosition = 0
    private var jumpSortIndex = ""
    private var scale = 0f
    private var current_Y = 0
    private var last_Y = 0
    private var fragmentList: MutableList<Fragment>? = ArrayList()

    override fun createLayout(): Int {
        return R.layout.aibk_fragment_model_splitlayout
    }

    override fun initView(view: View?) {
        scale = resources.displayMetrics.density
        rootView = view
        rootView!!.RlAudioPlayer.visibility = View.GONE
        rootView!!.RlArticleView.visibility = View.GONE

        showQuestionView()
    }

    /*
    * 显示试题内容
    * */
    private fun showQuestionView() {

        rootView!!.RlEvaluationButtonView.visibility = View.VISIBLE
        rootView!!.BtnEvaluationQues.setOnClickListener(this)
        rootView!!.BtnEvaluationQues.addClickScale()
        //隐藏单题评估系数
        rootView!!.RlQuesAssessment.visibility = View.GONE

        //是否显示来源
        var resource = paperEvaluationInfor.TypeList[index_A].QuesDetailList[index_B].Resource
        if (resource.isEmpty()) {
            rootView!!.IncludeQuesInformationView.TvSourceFrom.visibility = View.INVISIBLE
        } else {
            rootView!!.IncludeQuesInformationView.TvSourceFrom.visibility = View.VISIBLE
            rootView!!.IncludeQuesInformationView.TvSourceFrom.text = "来源: $resource"
        }
        //显示试题准确率
        var quesScoreRate = paperEvaluationInfor.TypeList[index_A].QuesList[index_B].ScoreRate
        if (quesScoreRate != "--") {
            quesScoreRate = "$quesScoreRate%"
        }
        rootView!!.IncludeQuesInformationView.TvScoreRate.text = "得分率: $quesScoreRate"

        //加载题干内容
        var ask = paperEvaluationInfor.TypeList[index_A].QuesDetailList[index_B].QuesBody
        val childAnswerType = getChildListBean(paperEvaluationInfor, index_A, index_B, 0).ChildAnswerType
        if (childAnswerType == 32) {//匹配题
            ask = getChildListBean(paperEvaluationInfor, index_A, index_B, 0).ChildAsk
        }
        ask = ask.replace("clickFunction", "Android.clickFunction")

        if (WebStyleUtils.hasTable(ask)) {
            WebStyleUtils.showWebViewCssStyle(activity, rootView!!.WvAsk, ask, false)
        } else {
            WebStyleUtils.showWebViewCssStyle(activity, rootView!!.WvAsk, ask, true)
        }
        rootView!!.WvAsk.addJavascriptInterface(
                JSInterface(
                        activity,
                        returnImageUrlsFromHtml(ask)
                ), "Android"
        )
        rootView!!.WvAsk.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                rootView!!.RlWebLoading.visibility = View.GONE
                WebStyleUtils.setWebImageClick(view, "Android")

                isAddView = true
                handler.sendEmptyMessageDelayed(0, 100)
            }
        }

        rootView!!.WvAsk.setOnScrollChangeListener(object : KWebView.OnScrollChangeListener {
            override fun onPageEnd(l: Int, t: Int, oldl: Int, oldt: Int) {
                Log.e("KWvA", "已经到达地端")
            }

            override fun onPageTop(l: Int, t: Int, oldl: Int, oldt: Int) {
                Log.e("KWvA", "已经到达顶端")
            }

            override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
                Log.e("KWvA", "=======oldt========$oldt")
                last_Y = oldt
            }
        })

        //加载作答区域
        fragmentList!!.clear()
        var childListSize = paperEvaluationInfor.TypeList[index_A].QuesDetailList[index_B].ChildList.size
        for (c in 0 until childListSize) {
            var childAnswerType = getChildListBean(paperEvaluationInfor, index_A, index_B, c).ChildAnswerType
            if (childAnswerType == 1) {//选择
                (fragmentList as ArrayList<Fragment>).add(
                        EvaluationFragmentParentXzt(activity, paperEvaluationInfor, index_A, index_B, c)
                )
            } else if (childAnswerType == 2 || childAnswerType == 4) {//简答
                (fragmentList as ArrayList<Fragment>).add(
                        EvaluationFragmentParentJdt(activity, paperEvaluationInfor, index_A, index_B, c)
                )
            } else if (childAnswerType == 32) {//匹配
                val itemListSize = getChildListBean(paperEvaluationInfor, index_A, index_B, c).ItemList.size
                for(d in 0 until itemListSize) {
                    (fragmentList as ArrayList<Fragment>).add(
                            EvaluationFragmentParentPpt(activity, paperEvaluationInfor, index_A, index_B, c,d)
                    )
                }
            }
        }

        val mAdapter = KBaseFragmentPagerAdapter(childFragmentManager, fragmentList as ArrayList<Fragment>)
        rootView!!.VpAnswer.adapter = mAdapter
        rootView!!.VpAnswer.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                childVpPosition = position
                showChildVpInfor()
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })
    }

    private fun showChildVpInfor() {
        val indexC = PaperEvaluationInforIndexHelp.ChildVpIndex_return_IndexC(paperEvaluationInfor,index_A,index_B,childVpPosition)
        var childAnswerType = getChildListBean(paperEvaluationInfor, index_A, index_B, indexC).ChildAnswerType
        if (childAnswerType == 1) {//选择
            rootView!!.TvChildAnswerCurrent.visibility = View.VISIBLE
        } else if (childAnswerType == 2 || childAnswerType == 4) {//简答
            rootView!!.TvChildAnswerCurrent.visibility = View.VISIBLE
        } else if (childAnswerType == 32) {//匹配
            rootView!!.TvChildAnswerCurrent.visibility = View.VISIBLE
        }
        val quesChildNum = paperEvaluationInfor.TypeList[index_A].QuesDetailList[index_B].QuesChildNum
        rootView!!.TvChildAnswerCount.text = Html.fromHtml(resources.getString(R.string.aibk_jdt_child_count, quesChildNum))
        rootView!!.TvChildAnswerCurrent.text = Html.fromHtml(resources.getString(R.string.aibk_current_child_vp, childVpPosition + 1, quesChildNum))
    }

    //JS点击事件处理
    inner class JSInterface(var context: Context, var imageUrls: Array<String>?) {

        @JavascriptInterface
        fun clickFunction(position: String) {
            activity.runOnUiThread {
                //在webview中进行点击选择需要作答的区间
                jumpSortIndex = position
                childVpPosition = PaperEvaluationInforIndexHelp.ItemSortIndex_return_IndexC(paperEvaluationInfor, position)
                showBlankView()
            }
        }

        //java回调js代码，不要忘了@JavascriptInterface这个注解，不然点击事件不起作用
        @JavascriptInterface
        fun openImage(img: String, pos: Int) {
            val paths = ArrayList<String>()
            paths.add(img)
            Log.e("openImage", "$pos========点击了图片=========$img")
            ShowDialogTools.showBigImageDialog(activity, img)
        }
    }

    private fun showBlankView() {

        var kWvHeight = rootView!!.WvAsk.height//获取当前webview控件的高度
        rootView!!.WvAsk.evaluateJavascript(
                "javascript:topHeight('blank$jumpSortIndex')",
                ValueCallback<String?> { value ->
                    val dp = Integer.valueOf(value!!)
                    current_Y = (Math.round(dp * scale) - kWvHeight / 2).toInt()//此处关键，保持被点击的区域处于可见区域中间位置
                    val anim: ObjectAnimator =
                            ObjectAnimator.ofInt(
                                    rootView!!.WvAsk, "scrollY", last_Y, current_Y
                            )
                    anim.setDuration(500).start()
                    last_Y = current_Y
                })

        val itemListSize = getChildListBean(paperEvaluationInfor, index_A, index_B, 0).ItemList.size
        for (d in 0 until itemListSize) {
            val itemSortIndex = getChildListBean(paperEvaluationInfor, index_A, index_B, 0).ItemList[d].SortIndex
            val itemAnswer = getChildListBean(paperEvaluationInfor, index_A, index_B, 0).ItemList[d].ItemAnswer

            if (itemSortIndex == jumpSortIndex) {
                rootView!!.WvAsk.loadUrl("javascript:setBackGroundColor('" + "blank" + itemSortIndex +
                        "','" + "#ceebff" + "','" + "5px" + "','" + "0px solid #ffffff" + "')")
            } else {
                rootView!!.WvAsk.loadUrl("javascript:setBackGroundColor('" + "blank" + itemSortIndex +
                        "','" + "#00000000" + "','" + "0px" + "','" + "1px solid #848484" + "')")
            }
            showBlankItemAnswer(itemSortIndex, itemAnswer)
        }
    }

    private fun showBlankItemAnswer(
            sortIndex: String,
            itemAnswer: String
    ) {
        rootView!!.WvAsk.loadUrl(
                "javascript:CalledByJavaCodeWithPara('" + "blank" + sortIndex
                        + "','" + "&nbsp&nbsp&nbsp&nbsp&nbsp"
                        + "<font color=\"#00b30d\">" + itemAnswer + "</font>"
                        + "&nbsp&nbsp&nbsp&nbsp&nbsp" + " ')"
        )

    }

    //答题卡跳转
    fun fragmentJumpToSortIndex(itemSortIndex: String) {
        childVpPosition = PaperEvaluationInforIndexHelp.ItemSortIndex_return_IndexC(paperEvaluationInfor, itemSortIndex)
        if(childVpPosition==0){
            jumpSortIndex = itemSortIndex
        }
        if(isAddView) {
            handler.sendEmptyMessageDelayed(0, 100)
        }
    }

    //答题卡跳转辅助方法
    private val handler = Handler(Handler.Callback { msg ->
        when (msg.what) {
            0 -> {
                if(jumpSortIndex.isEmpty()){
                    jumpSortIndex =  getChildListBean(paperEvaluationInfor, index_A, index_B, 0).ItemList[0].ItemSortIndex
                }
                showChildVpInfor()
                rootView!!.VpAnswer.setCurrentItem(childVpPosition, true)
                var childAnswerType = getChildListBean(paperEvaluationInfor, index_A, index_B, 0).ChildAnswerType
                if (childAnswerType == 32) {
                    showBlankView()
                }
            }
        }
        false
    })

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.BtnEvaluationQues ->{
                MyToast.showToast("跳转到教师端讲评界面--综合题")
            }
        }
    }
}